import { Ai } from '@cloudflare/ai';
import { filterQueryTimestamp } from './filter.js'

function checkInput(inputs) {
  const demo = {
    text: 'Tell me a joke about Cloudflare',
    source_lang: 'en',
    target_lang: 'zh'
  };

  if (!inputs) {
    console.log('no inputs');
    return Response.json({ msg: 'inputs format error, must like demo', demo: demo });
  }

  if (!inputs.text) {
    console.log('no inputs.text');
    return Response.json({ msg: 'inputs format error, must like demo', demo: demo });
  }

  if (!inputs.source_lang) {
    console.log('no inputs.source_lang');
    return Response.json({ msg: 'inputs format error, must like demo', demo: demo });
  }

  if (!inputs.target_lang) {
    console.log('no inputs.target_lang');
    return Response.json({ msg: 'inputs format error, must like demo', demo: demo });
  }
}

export default {
  async fetch(request, env) {
    console.log(request.method);
    
    if(request.method == 'GET'){
      var url = new URL(request.url);
  
      var curl = `curl --location --request GET 'https://${url.host}/?t=$timestamp' \\
      --header 'Token: SHA256('Time'+$t + $env.FilterSecret).Hex' \\
      --header 'Content-Type: application/json' \\
      --data '{
          "text": "Tell me a joke about Cloudflare",
          "source_lang": "en",
          "target_lang": "zh"
      }'`
      return new Response(curl);
    }

    var requestJson = await request.json()
    var checkResult = checkInput(requestJson);
    if (checkResult) {
      return checkResult;
    }

    var result = filterQueryTimestamp(request, env)
    if (result) {
      return result;
    }

    const ai = new Ai(env.AI);
    const response = await ai.run('@cf/meta/m2m100-1.2b', requestJson);

    return Response.json(response);
  }
};
